﻿/*
* Activity Tracking Log v0.1.1 - http://activitytrackinglog.codeplex.com
* Activity Tracking Log for ASP.Net & ASP.Net MVC
* Copyright (c) 2011 Vadim Burac
* Licensed under the Microsoft Public License (Ms-PL)
* http://activitytrackinglog.codeplex.com/license
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ActivityTrackingLog.Data;
using System.Linq.Expressions;

namespace ActivityTrackingLog.Storage.Implementations
{
    internal class InMemoryContext : BaseContext
    {
        #region ctors

        public InMemoryContext()
        {

        }

        #endregion

        #region command methods

        public override void ReleaseResources()
        {
            base.ReleaseResources();
        }

        #endregion

        #region entity related logic

        public override IQueryable<T> GetQuery<T>()
        {
            if (typeof(T) == typeof(ActivityItem))
                return ActivityItemsList.Cast<T>().AsQueryable<T>();
            if (typeof(T) == typeof(UserAgentItem))
                return UserAgentItemsList.Cast<T>().AsQueryable<T>();

            return null;
        }

        public override void Add(ActivityItem item)
        {
            SaveUserAgentItem(item.UserAgentItem);
            
            // increment sequence
            item.Sequence = ActivityItemsList.Count;
            ActivityItemsList.Add(item);
        }

        public override void RemoveAll(Expression<Func<ActivityItem, bool>> predicate)
        {
            var func = predicate.Compile();
            ActivityItemsList.RemoveAll(item => func(item));
        }

        public override int Count()
        {
            return ActivityItemsList.Count;
        }

        #endregion

        #region helpers

        private void SaveUserAgentItem(UserAgentItem item)
        {
            if (null != item && item.IsNew)
            {
                item.Sequence = UserAgentItemsList.Count;
                UserAgentItemsList.Add(item);
            }
        }

        private List<ActivityItem> ActivityItemsList
        {
            get
            {
                return InMemoryRepository.ActivityListStorage;
            }
        }

        private List<UserAgentItem> UserAgentItemsList
        {
            get
            {
                return InMemoryRepository.UserAgentListStorage;
            }
        }


        #endregion
    }
}
